package dfs;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * leet-code(46): 全排列
 *
 * @author Ringo
 * @date 2021/8/14 14:01
 */
public class Permute {

    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        System.out.println(newInstance().permute(nums));
    }

    public static Permute newInstance() {
        return new Permute();
    }

    public List<List<Integer>> permute(int[] nums) {
        // 参数判断
        if (Objects.isNull(nums) || nums.length == 0)
            return new ArrayList<>();
        // 递归参数初始化
        List<List<Integer>> ans = new LinkedList<>();
        List<Integer> list = new LinkedList<>();
        boolean[] visited = new boolean[nums.length];

        // 递归
        dfs(nums, ans, list, visited);

        return ans;
    }

    /**
     * 递归
     *
     * @param nums    目标数组
     * @param ans     结果集
     * @param list    临时保存每次递归结果
     * @param visited 访问数组
     */
    private void dfs(int[] nums, List<List<Integer>> ans, List<Integer> list, boolean[] visited) {
        if (list.size() >= nums.length) {
            ans.add(new ArrayList<>(list));
            return;
        }

        for (int i = 0; i < nums.length; ++i) {
            if (visited[i]) continue;
            list.add(nums[i]);
            visited[i] = true;

            dfs(nums, ans, list, visited);

            list.remove(list.size() - 1);
            visited[i] = false;
        }
    }

}
